package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.pay.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import entity.IdWorker;
import entity.Result;
import entity.StatusCode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述
 *
 * @author ljh
 * @version 1.0
 * @package com.changgou.pay.controller *
 * @Date 2019-12-8
 * @since 1.0
 */
@RestController
@RequestMapping("/weixin/pay")
public class WeixinPayController {
    @Autowired
    private WeixinPayService weixinPayService;


    @Autowired

    private IdWorker idWorker;


    /**
     *
     * @param parameter 包含了订单号,和 金额以及 队列名 交互机 路由key
     * @return
     */
    @RequestMapping("/createNative")
    public Result<Map<String, String>> createNative(@RequestParam(required = false) Map<String,String> parameter) {
//        String total_fee = "1";//1分钱
//        long outtradeno = idWorker.nextId();//生成的订单号
        //获取tokendecode获取到用户名
        Map<String, String> map = weixinPayService.createNative(parameter);
        return new Result<Map<String, String>>(true, StatusCode.OK, "生成二维码成功", map);
    }

    /**
     * 查询指定的交易订单号对应的支付的状态
     *
     * @param out_trade_no
     * @return
     */
    @RequestMapping("/status/query")
    public Result<Map<String, String>> queryStatus(String out_trade_no) {

        Map<String, String> result = weixinPayService.queryStatus(out_trade_no);
        return new Result<Map<String, String>>(true, StatusCode.OK, "查询订单的状态成功", result);
    }

    @Autowired

    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment env;

    /**
     * 接收微信发送过来的请求 获取到支付的结果通知
     */
    @RequestMapping("/notify/url")
    public String notifyurl(HttpServletRequest request) {

        System.out.println("收到了微信给的信息");

        ServletInputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            //1.获取流信息
            inputStream = request.getInputStream();
            //2.转换成字节数组
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, len);
            }
            //3.转成字符串(XML)
            byte[] bytes1 = byteArrayOutputStream.toByteArray();
            String resultstring = new String(bytes1, "utf-8");
            System.out.println(resultstring);
            //4.转换成map 做业务的处理
            Map<String, String> resultmap = WXPayUtil.xmlToMap(resultstring);

            String attach = resultmap.get("attach");//JSON格式的字符串(包含:发送过来的队列名和路由key和交换机)

            Map<String,String> attachMap = JSON.parseObject(attach, Map.class);


//            resultmap.put("username","szitheima");


            String exchange = attachMap.get("exchange");//获取到交换机的数据()
            String routingkey = attachMap.get("routingkey");//获取到路由key的数据

            //发送消息  需要 微信支付系统 传递 (又是由用户传递给微信的支付系统)信息,判断 如果是普通订单 发送普通的消息   如果是秒杀的发送秒杀的消息
            rabbitTemplate.convertAndSend(exchange, routingkey, JSON.toJSONString(resultmap));

            //5.返回给微信的字符串XML
            Map<String, String> resultweix = new HashMap<>();
            resultweix.put("return_code", "SUCCESS");
            resultweix.put("return_msg", "OK");

            String s = WXPayUtil.mapToXml(resultweix);

            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
